package com.tyssq.transit.services.controller;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Enumeration;

/**
 * <p>
 *
 * </p>
 *
 * @author liaozhenghan
 * @date 2023-12-12 10:50:00
 */
@RestController
@Data
@ConfigurationProperties(prefix = "proxy")
public class ProxyController {
    private String targetHost;
    private int targetPort;

    @RequestMapping("/**")
    public ResponseEntity<String> forwardRequest(@RequestBody(required = false) String body,
                                                 HttpMethod method,
                                                 HttpServletRequest request) throws URISyntaxException {
        String requestUrl = request.getRequestURI();

        URI uri = new URI("http", null, targetHost, targetPort, null, null, null);
        uri = UriComponentsBuilder.fromUri(uri)
                .path(requestUrl)
                .query(request.getQueryString())
                .build()
                .toUri();

        HttpHeaders headers = new HttpHeaders();
        headers.putAll(getRequestHeaders(request));

        HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(uri, method, httpEntity, String.class);

        return new ResponseEntity<>(responseEntity.getBody(), responseEntity.getHeaders(), responseEntity.getStatusCode());
    }

    private HttpHeaders getRequestHeaders(HttpServletRequest request) {
        HttpHeaders headers = new HttpHeaders();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String s = headerNames.nextElement();
            headers.add(s, request.getHeader(s));
        }
        return headers;
    }
}
